<template>
  <div class="common-container">
    <div class="header">
      <div class="header_left" style="display: flex;align-items: center;">
        <el-select size="small" v-model="searchSel" slot="prepend" placeholder="请选择" class="el_Select sel_prepend">
          <el-option label="姓名" value="1"></el-option>
          <el-option label="联系电话" value="2"></el-option>
        </el-select>
        <el-input :placeholder="searchSel == 1 ? '请输入姓名' : '请输入手机号或座机号'" v-model="searchVal"
          style="width: 240px;margin-right: 15px;" size="small" maxlength="20" clearable @clear="clearSearchVal"
          class="el_input">
          <el-button slot="append" :icon="loadingSearch ? 'el-icon-loading' : 'el-icon-search'" @click="searchClick">
          </el-button>
        </el-input>

        <el-popover placement="bottom" width="460" trigger="click" popper-class="popover" size="small"
          v-model="showPopover">
          <div>
            <el-form label-width="70px" style="margin: 20px 0" class="popover_from">
              <el-form-item size="small" label="组织机构"
                v-if="user.roleName === 'TENANT_ADMIN' || user.roleName === 'ORG_ADMIN'">
                <TreeSearch style="width: 360px;margin-left: 15px;" ref="refTreeSearch" @changeOrgId="changeOrgId">
                </TreeSearch>
              </el-form-item>
              <el-form-item size="small" label="联网单位">
                <el-select size="small" style="width: 360px;margin-left: 15px;" clearable v-loadMore="loadMore"
                  v-model='selectedValue' placeholder='请选择联网单位' filterable>
                  <el-option v-for='item in orgList' :label='item.orgName' :value='item.id' :key='item.id'>
                  </el-option>
                  <div class="div_box" v-loading="loading" :style="loading ? '' : 'display: none;'"> </div>
                </el-select>
              </el-form-item>
            </el-form>
            <div class="footer" style="text-align: right">
              <el-button size="small" @click="resetClick" class="cancel-button">重 置</el-button>
              <el-button size="small" class="confirm-button" @click="onSearch">确 定</el-button>
            </div>
          </div>
          <el-button size="small" slot="reference" :class="hasSearch ? 'elhasSearch elhasSearch2' : 'elhasSearch2'">
            高级搜索<i class="el-icon-search" style="margin-left: 5px; font-size: 12px"></i></el-button>
        </el-popover>

      </div>
      <div class="header_right">
        <el-button size="small" icon="el-icon-plus" @click="addClick" v-permission="{ action: 'alarmReceiver:add' }">
          新增
        </el-button>
        <el-button size="small" class="el_button" @click="importClick" icon="el-icon-download"
          v-permission="{ action: 'alarmReceiver:import' }">导入</el-button>
        <!-- <el-button size="small" icon="el-icon-delete" @click="batchDelClick">批量删除</el-button> -->
        <el-dropdown @command="onDropdown">
          <el-button size="small" style="margin-left: 15px;">
            批量操作<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="del">批量删除</el-dropdown-item>
            <el-dropdown-item command="export">批量导出</el-dropdown-item>
            <el-dropdown-item command="commandTime">批量设置接警时段</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <div class="content">
      <el-table :data="dataList" height="calc(100% - 65px)" class="table" ref="refTable" row-key="id"
        :header-cell-style="headerStyle" @selection-change="batchSelect" v-loading="loadingTable"
          element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(47, 51, 73, 0.3)">
        <el-table-column align="center" type="selection" :reserve-selection="true" width="60"></el-table-column>
        <el-table-column align="center" label="序号" type="index" width="80" height="30"></el-table-column>
        <el-table-column align="center" prop="orgName" label="联网单位" min-width="120"
          show-overflow-tooltip></el-table-column>
        <el-table-column align="center" prop="name" label="姓名" min-width="100" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" prop="mobile" label="联系电话" min-width="100" show-overflow-tooltip>
        </el-table-column>
        <!-- <el-table-column align="center" prop="address" label="关联安装点" min-width="90">
          <template slot-scope="{ row }">
            <span @click="searchSpaceClick(row)" class="search_space">查看</span>
          </template>
</el-table-column> -->
        <el-table-column align="center" prop="type" label="通知方式" min-width="150">
          <template slot-scope="{ row }">
            {{ row.mobileReceive ? "语音" : "" }}
            {{ row.mobileReceive && row.msgReceive ? "，" : "" }}
            {{ row.msgReceive ? "短信" : "" }}
            {{ row.mpReceive && row.msgReceive ? "，" : "" }}
            {{
              row.mobileReceive && row.mpReceive && !row.msgReceive ? "，" : ""
            }}
            {{ row.mpReceive ? "公众号" : "" }}
          </template>
        </el-table-column>
        <!-- <el-table-column
          align="center"
          prop="type"
          label="通知方式"
          width="360"
        >
          <template slot-scope="{ row }">
            <el-switch
              v-model="row.mobileReceive"
              inactive-text="手机号"
              active-color="#7367f0"
              :active-value="1"
              :inactive-value="0"
              @change="switchChange1(row)"
            >
            </el-switch>
            <el-switch
              v-model="row.msgReceive"
              inactive-text="短信"
              active-color="#7367f0"
              :active-value="1"
              :inactive-value="0"
              @change="switchChange2(row)"
            >
            </el-switch>
            <el-switch
              v-model="row.mpReceive"
              inactive-text="公众号"
              active-color="#7367f0"
              :active-value="1"
              :inactive-value="0"
              @change="switchChange3(row)"
            >
            </el-switch>
          </template>
        </el-table-column> -->
        <el-table-column align="center" label="操作" width="180">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="接警时段" placement="bottom"
              v-permission="{ action: 'alarmReceiver:time' }">
              <i @click="timeClick(scope.row)" class="iconfont shijian tableBtnIcon"></i>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="配置接警人" placement="bottom"
              v-permission="{ action: 'alarmReceiver:configure' }">
              <i @click="searchSpaceClick(scope.row)" class="iconfont jingwuicon_svg- tableBtnIcon"></i>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="编辑" placement="bottom"
              v-permission="{ action: 'alarmReceiver:edit' }">
              <i @click="editClick(scope.row)" class="iconfont tianxie tableBtnIcon"></i>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="bottom"
              v-permission="{ action: 'alarmReceiver:delete' }">
              <i @click="delClick(scope.row)" class="iconfont shanchu tableBtnIcon"></i>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination :page.sync="page" :limit.sync="limit" :total="total" @pagination="getDataList" class="pagination">
      </pagination>
    </div>
    <alarm-receiver-add ref="refAdd"></alarm-receiver-add>
    <alarm-receiver-edit ref="refEdit" :editData="editData" @clearEditData="clearEditData"></alarm-receiver-edit>
    <receiver-space ref="refSpace" :spaceData="spaceData"></receiver-space>
    <editTime ref="refeditTime" :spaceData="spaceData" :batchDataListId="batchDataListId"></editTime>
    <ImportDevice ref="refImportDevice"></ImportDevice>
  </div>
</template>

<script>
import {
  reqAlarmReceiverList,
  reqAlarmReceiverDel,
  reqAlarmReceiverEdit,
  reqAlarmReceiverBatchDel,
  reqOrgList,
} from "@api/api.js";
import tableStyleMixin from "@mixin/table-style";
import Pagination from "@components/Pagination.vue";
import AlarmReceiverAdd from "./components/AlarmReceiverAdd.vue";
import AlarmReceiverEdit from "./components/AlarmReceiverEdit.vue";
import ReceiverSpace from "./components/ReceiverSpace.vue";
import editTime from "./components/editTime.vue";
import ImportDevice from "./components/ImportDevice.vue";
// import batchDel from "@views/mixins/batchDel.js";
import { mapState } from "vuex";
import loadMore from "@mixin/loadMore";
const statusType = [{
  key: "1",
  value: "语音",
},
{
  key: "0",
  value: "",
},
];
const transstatusType = statusType.reduce((acc, cur) => {
  acc[cur.key] = cur.value;
  return acc;
}, {});

const msgReceive = [{
  key: "1",
  value: "短信",
},
{
  key: "0",
  value: "",
},
];
const msgReceiveType = msgReceive.reduce((acc, cur) => {
  acc[cur.key] = cur.value;
  return acc;
}, {});

const mpReceive = [{
  key: "1",
  value: "公众号",
},
{
  key: "0",
  value: "",
},
];
const mpReceiveType = mpReceive.reduce((acc, cur) => {
  acc[cur.key] = cur.value;
  return acc;
}, {});
import TreeSearch from "@components/TreeSearch.vue";

export default {
  name: "alarmReceiver",
  components: {
    Pagination,
    AlarmReceiverAdd,
    AlarmReceiverEdit,
    ReceiverSpace,
    editTime,
    ImportDevice,
    TreeSearch
  },
  mixins: [tableStyleMixin, loadMore],
  data() {
    return {
      page: 1,
      limit: 10,
      total: 0,
      dataList: [],
      searchVal: "",
      searchSel: "1", //名/手机号
      orgId: "", //搜索条件
      orgList: [],
      loadingSearch: false,
      editData: {}, //编辑信息
      spaceData: {}, //查看关联空间
      batchDataList: [],
      sysInstanceIndex: 1,
      sysInstanceTotalPages: 10,
      flag: true,
      loading: false,
      batchDataListId: [],
      orgName: '',
      selectedValue: '',
      targetId: "",
      organParams: {},
      showPopover: false, //v-model默认值是false, click激活变成true
      hasSearch: false,
      loadingTable:false,
    };
  },
  computed: {
    ...mapState(["user", "spacesManage"]),
  },
  mounted() {
    // if (this.user.roleName == 'ORG_ADMIN' || this.user.roleName == 'INSTERALL_USER') {
    //   // 组织||装维
    //   this.parentId = this.spacesManage.organizationInfo.orgId;
    //   this.getDataList();
    // }else{
    //   this.getDataList();
    // }
    if (this.user.roleName == 'INSTERALL_USER' || this.user.roleName == 'UNIT_ADMIN') {
      this.getOrgList()
    }
    this.getDataList();
  },

  methods: {
    // 搜索
    async onSearch() {
      this.page = 1;
      this.limit = 10;
      this.showPopover = false;
      this.getDataList()
    },
    // 高级搜索重置
    async resetClick() {
      this.parentId = ''
      this.selectedValue = ''
      this.page = 1;
      this.limit = 10;
      await this.getDataList()
      if (this.$refs.refTreeSearch) {
        this.$refs.refTreeSearch.onclose()
      }
      if (this.user.roleName != 'INSTERALL_USER' && this.user.roleName != 'UNIT_ADMIN') {
        this.orgList = []
      }
    },
    changeOrgId(instanceId) {
      this.parentId = instanceId.id
      this.handleClear();
    },
    onClear() {
      this.parentId = this.spacesManage.organizationInfo.orgId || '';
      this.getInitDataList();
    },
    // 清空
    handleClear() {
      this.selectedValue = '';
      this.orgName = '';
      this.sysInstanceIndex = 1;
      this.sysInstanceTotalPages = 10;
      this.orgList = []
      this.getOrgList()
    },
    // 远程搜索
    async remoteMethod(query) {
      this.selectedValue = query //保留输入的值
      this.orgName = query;
      this.sysInstanceIndex = 1;
      this.sysInstanceTotalPages = 10;
      this.orgList = []
      this.getOrgList()
    },
    async loadMore() {
      if (this.sysInstanceIndex >= Math.ceil(this.sysInstanceTotalPages / 10)) return
      this.sysInstanceIndex++
      this.loading = true;
      await this.getOrgList()
      this.loading = false;
    },
    // 请求单位列表
    async getOrgList() {
      let { tenantId, userId, roleName } = this.user;
      const res = await reqOrgList({
        tenantId,
        userId,
        roleName,
        orgName: this.orgName,
        parentId: this.parentId,
        type: "4"
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.orgList = res.data.rows
    },
    // 获取接警人列表
    async getDataList() {
      let name = "";
      let mobile = "";
      if (this.searchSel == 1) {
        name = this.searchVal;
        mobile = "";
      } else {
        mobile = this.searchVal;
        name = "";
      }
      let params = {
        userId: this.user.userId,
        roleName: this.user.roleName,
        orgId: this.selectedValue == '' ? this.parentId : this.selectedValue,//机构||单位
        name,
        mobile,
      };
      this.loadingTable = true;
      const res = await reqAlarmReceiverList(this.page, this.limit, params);
      this.loadingTable = false;
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.hasSearch = (this.parentId || this.selectedValue) ? true : false
      this.dataList = res.data.rows;
      this.total = res.data.total;
    },
    getInitDataList() {
      this.page = 1;
      this.limit = 10;
      this.getDataList();
      this.clearSelections();
    },
    // 搜索
    async searchClick() {
      this.page = 1;
      this.limit = 10;
      this.loadingSearch = true;
      await this.getDataList();
      this.loadingSearch = false;
      this.clearSelections();
    },
    // 清除请求
    clearSearchVal() {
      this.getInitDataList();
    },
    // 新增
    addClick() {
      this.$refs.refAdd.dialogVisible = true;
      if (this.user.roleName == 'INSTERALL_USER' || this.user.roleName == 'UNIT_ADMIN') {
        this.$refs.refAdd.getOrgList()
      }
    },
    // 导入
    importClick() {
      // this.$refs.refImportDevice.getManufacturerList();
      this.$refs.refImportDevice.dialogVisible = true;
    },
    // 查看关联安装点
    searchSpaceClick(row) {
      this.spaceData = JSON.parse(JSON.stringify(row));
      this.$refs.refSpace.dialogVisible = true;
    },
    timeClick(row) {
      // console.log(row);
      this.batchDataListId = []
      this.spaceData = JSON.parse(JSON.stringify(row));
      this.$refs.refeditTime.dialogVisible = true;
    },
    // 编辑
    editClick(row) {
      this.editData = JSON.parse(JSON.stringify(row));
      this.$refs.refEdit.dialogVisible = true;
    },
    // 清除editData
    clearEditData() {
      this.editData = {};
    },
    // 修改通知方式--手机号
    switchChange1(row) {
      let { id, mobile, name, mobileReceive, msgReceive, mpReceive, parkId } =
        row;
      let params = {
        id,
        mobile,
        name,
        mobileReceive,
        msgReceive,
        mpReceive,
        parkId,
      };
      if (mobileReceive == 1) {
        this.$confirm(
          `此操作将开启${name}的手机号通知方式, 是否继续?`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(async () => {
            params.mobileReceive = 1;
            this.reqEditFun(params);
            row.mobileReceive = 1;
          })
          .catch(() => {
            row.mobileReceive = 0;
          });
      } else {
        this.$confirm(
          `此操作将关闭${name}的手机号通知方式, 是否继续?`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(async () => {
            params.mobileReceive = 0;
            this.reqEditFun(params);
            row.mobileReceive = 0;
          })
          .catch(() => {
            row.mobileReceive = 1;
          });
      }
    },
    // 短信
    switchChange2(row) {
      let { id, mobile, name, mobileReceive, msgReceive, mpReceive, parkId } =
        row;
      let params = {
        id,
        mobile,
        name,
        mobileReceive,
        msgReceive,
        mpReceive,
        parkId,
      };
      if (msgReceive == 1) {
        this.$confirm(`此操作将开启${name}的短信通知方式, 是否继续?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            params.msgReceive = 1;
            this.reqEditFun(params);
            row.msgReceive = 1;
          })
          .catch(() => {
            row.msgReceive = 0;
          });
      } else {
        this.$confirm(`此操作将关闭${name}的短信通知方式, 是否继续?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            params.msgReceive = 0;
            this.reqEditFun(params);
            row.msgReceive = 0;
          })
          .catch(() => {
            row.msgReceive = 1;
          });
      }
    },
    // 公众号
    switchChange3(row) {
      let { id, mobile, name, mobileReceive, msgReceive, mpReceive, parkId } =
        row;
      let params = {
        id,
        mobile,
        name,
        mobileReceive,
        msgReceive,
        mpReceive,
        parkId,
      };
      if (mpReceive == 1) {
        this.$confirm(
          `此操作将开启${name}的公众号通知方式, 是否继续?`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(async () => {
            params.mpReceive = 1;
            this.reqEditFun(params);
            row.mpReceive = 1;
          })
          .catch(() => {
            row.mpReceive = 0;
          });
      } else {
        this.$confirm(
          `此操作将关闭${name}的公众号通知方式, 是否继续?`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(async () => {
            params.mpReceive = 0;
            this.reqEditFun(params);
            row.mpReceive = 0;
          })
          .catch(() => {
            row.mpReceive = 1;
          });
      }
    },
    // 请求编辑通知方式
    async reqEditFun(params) {
      const res = await reqAlarmReceiverEdit(params);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$modal.notifySuccess("修改成功");
    },
    // 删除
    async delClick(row) {
      const result = await this.$confirm(
        `此操作将删除接警人：${row.name}, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => { });
      if (result !== "confirm") return;
      this.reqDelFun([row.id]);
    },
    // 点击复选框触发，可跨分页选择
    batchSelect(arr) {
      this.batchDataList = arr;
    },
    // 更多操作回调事件
    async onDropdown(e) {
      if (this.batchDataList.length <= 0) {
        this.$modal.notifyWarning("请先勾选需要操作的接警人");
        return;
      }
      switch (e) {
        case "del":
          const result = await this.$confirm(
            "此操作将永久删除勾选的接警人, 是否继续?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          ).catch(() => { });
          if (result !== "confirm") return;
          let arrId = this.batchDataList.map((item) => {
            return item.id;
          });
          this.reqDelFun(arrId);
          break;
        case "export":
          // 前端实现导出
          import("@/vendor/Export2Excel").then((excel) => {
            // 设置Excel的表格第一行的标题
            const tHeader = ['姓名', '联系电话', '通知方式', '通知方式', '通知方式', '单位'];
            //  'date', 'struct1', 'struct2'对象的属性
            const filterVal = ['name', 'mobile', 'mobileReceive', 'msgReceive', 'mpReceive', 'orgName'];

            const list = this.batchDataList; // 数据集
            const data = this.formatJson(filterVal, list);

            excel.export_json_to_excel({
              header: tHeader, //表头
              data, //json数据
              filename: "接警人列表", //导出文件名
              autoWidth: true, //宽度是否自适应
              bookType: "xlsx", //导出文件后缀名
            });
            this.$modal.notifySuccess("导出成功，请在任务管理中查看");
            this.getInitDataList()
          });
          break;
        case "commandTime":
          this.batchDataListId = this.batchDataList.map((item) => {
            return item.id;
          });
          this.$refs.refeditTime.dialogVisible = true;
          break;
      }
    },
    // 导出处理数据
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          if (j === "mobileReceive") {
            return transstatusType[v[j]];
          }
          if (j === "msgReceive") {
            return msgReceiveType[v[j]];
          }
          if (j === "mpReceive") {
            return mpReceiveType[v[j]];
          }
          return v[j];
        })
      );
    },
    // 批量删除
    // async batchDelClick() {
    //   let { batchDataList } = this;
    //   if (batchDataList.length <= 0)
    //     return this.$modal.notifyWarning("请先勾选需要删除的接警人");
    //   const result = await this.$confirm(
    //     "此操作将永久删除勾选的接警人, 是否继续?",
    //     "提示",
    //     {
    //       confirmButtonText: "确定",
    //       cancelButtonText: "取消",
    //       type: "warning",
    //     }
    //   ).catch(() => { });
    //   if (result !== "confirm") return;
    //   let arrId = batchDataList.map((item) => {
    //     return item.id;
    //   });
    //   this.reqDelFun(arrId);
    // },
    // 清空复选框√√
    clearSelections() {
      this.$refs.refTable.clearSelection();
    },
    // 请求删除
    async reqDelFun(receiverIdList) {
      const res = await reqAlarmReceiverBatchDel({ receiverIdList });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$modal.notifySuccess("删除成功");
      this.getInitDataList();
    },
  },
};
</script>

<style scoped lang="less">
@import url("~@views/style/tablePage.less");
@import url("~@views/style/tree.less"); //左侧组织机构样式

.header_left {
  display: flex;
}

.input_box {
  margin-right: 15px;
}

// 查看关联安装点
.search_space {
  padding: 0 10px;
  cursor: pointer;

  &:hover {
    color: #7367f0;
  }
}

::v-deep .el-button--small {
  background: #7367f0;
  color: #fff;
  border: none;
}

// 下拉框加载开始
.div_box {
  height: 276px;
  position: absolute;
  top: -1px;
  left: -1px;
  width: 100%;
  z-index: 9999;
  // background: red;
  // opacity: 0.5;
}

::v-deep .el-loading-mask {
  border-radius: 4px;
}

// 下拉框加载结束


// 查询条件切换
::v-deep .sel_prepend .el-input {
  width: 100px;
}

// 查询条件切换
::v-deep .el-input-group__prepend {
  // border-left: none !important;
  // border-top: none !important;
  // border-bottom: none !important;
  // border-right: none !important;
}

// 搜索框
::v-deep .el_input .el-input__inner {
  border-left: none !important;
  border-radius: 0px !important;
}

::v-deep .el_Select .el-input__inner {
  border-radius: 0px !important;
}

// 高级搜索
::v-deep .el-button--primary {
  background-color: #7367f0;
  border: 1px solid #7367f0;
  color: #fff;
}

::v-deep .el-form-item__label {
  color: @primaryThemeTxtColor2;
  padding: 0px;
}

::v-deep .el-input__inner {
  color: var(--primaryContentTxt, #f1f1f1) !important;
}

.dropdown {
  background: #7367f0;
  color: #fff;
  border: none;
}

::v-deep .el-button--small {
  border: none;
}

// 高级搜索----------</style>